﻿using System;
using System.Globalization;
using Designit.Umb.Newsletter.Bll;

namespace Designit.Umb.Newsletter.Custom.designit.newsletter
{
    public partial class ScheduledSend : System.Web.UI.Page
    {
        private static bool _IsRunning;
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!_IsRunning)
                StartSendning();
        }

        private static void StartSendning()
        {
            _IsRunning = true;

            var datetime = DateTime.UtcNow;
            using (var reader = umbraco.BusinessLogic.Application.SqlHelper.ExecuteReader("select * from newsLetterCampaignDelayedSend"))
            {
                while (reader.Read())
                {
                    var localCampTime = DateTime.Parse(reader.GetString("timeStamp"));
                    var campTimeZoneId = reader.GetString("timezone");
                    var campTZI = TimeZoneInfo.FindSystemTimeZoneById(campTimeZoneId);
                    var temp = datetime.Add(campTZI.GetUtcOffset(localCampTime));
                    if (temp >= localCampTime)
                    {
                        EmbedNewsletter.SendCampaign(reader.GetInt("campaignId"));
                        umbraco.BusinessLogic.Application.SqlHelper.ExecuteNonQuery(
                            "delete from newsLetterCampaignDelayedSend where id=@id",
                            umbraco.BusinessLogic.Application.SqlHelper.CreateParameter("@id", reader.GetInt("id")));
                    }
                }
            }
            _IsRunning = false;
        }
    }
}
